/*
 * @lc app=leetcode.cn id=145 lang=javascript
 *
 * [145] 二叉树的后序遍历
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
// 非递归版 leetcode
var postorderTraversal = function(root) {
  const stack = []
  const res = []
  let current = root
  // 标记右子树是否访问完毕
  let prev = null
  while (current || stack.length) {
    while (current) {
      stack.push(current)
      current = current.left
    }
    current = stack.pop()
    if (!current.right || current.right === prev) {
      res.push(current.val)
      prev = current
      current = null
    } else {
      stack.push(current)
      current = current.right
    }
  }
  return res
};
// @lc code=end

// 递归版
// var postorderTraversal = function(root, res = []) {
//   if (root) {
//     postorderTraversal(root.left, res)
//     postorderTraversal(root.right, res)
//     res.push(root.val)
//   }
//   return res
// };

// 非递归版
// 自己实现的
// var postorderTraversal = function(root) {
//   const stack = []
//   const res = []
//   let current = root
//   while (current || stack.length) {
//     while (current) {
//       stack.push(current)
//       current = current.left
//     }
//     current = stack.pop()
//     let tempNode = {val: current.val}
//     // 先读右边节点
//     // 如果有右边节点，那么把当前节点保留在当前栈的位置，先读取右边节点
//     // 没有右边节点，那么直接添加到结果列表
//     current = current.right
//     if (!current) {
//       res.push(tempNode.val)
//     } else {
//       stack.push(tempNode)
//     }
//   }
//   return res
// };